package com.acerola.mrpc.protocol;

import com.acerola.mrpc.message.RpcProtocol;
import com.acerola.mrpc.serializer.ISerializer;
import com.acerola.mrpc.serializer.SerializerManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: mrpc
 * @description: 消息编码
 * @author: Acerola
 * @create: 2022-12-13 18:42
 **/
@Slf4j
public class MessageEncode extends MessageToByteEncoder<RpcProtocol<Object>> {

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcProtocol<Object> rpcProtocol, ByteBuf buffer) throws Exception {
        log.debug("========begin RpcEecoder==========");
        Header header = rpcProtocol.getHeader();
        //写入header
        buffer.writeShort(header.getMagic());
        buffer.writeByte(header.getVersion());
        buffer.writeByte(header.getSerializeType());
        buffer.writeByte(header.getMessageType());
        buffer.writeLong(header.getRequestId());
        //写入内容
        ISerializer serializer = SerializerManager.getSerializer(header.getSerializeType());
        byte[] serialize = serializer.serialize(rpcProtocol.getContent());
        buffer.writeInt(serialize.length);
        buffer.writeBytes(serialize);
    }
}
